package com.tedu.ds.sessionAndMessage.rabbitMq;

import com.tedu.ds.sessionAndMessage.config.RabbitMQConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.tedu.ds.sessionAndMessage.config.RabbitFanoutConfig.uuid;

@Component
@Slf4j
public class Producer {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送持久化的消息到 RabbitMQ
     * @param msg 消息
     */
    public void sendMessage(String msg) throws Exception{
        log.info("开始发送消息: {}", msg);
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (!ack) {
                log.error("消息发送失败，correlationData: {}, cause: {}", correlationData, cause);
            }
        });
        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
            log.warn("消息被退回，replyCode: {}, replyText: {}, exchange: {}, routingKey: {}", replyCode, replyText, exchange, routingKey);
        });

        // 创建持久化的消息
        Message message = MessageBuilder.withBody(msg.getBytes("UTF-8"))
                .setDeliveryMode(MessageDeliveryMode.PERSISTENT)  // 设置消息为持久化
                .build();

        // 发送消息
        rabbitTemplate.send(RabbitMQConfig.EXCHANGE_NAME, RabbitMQConfig.ROUTING_KEY+uuid, message);

    }
}